const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const session = require('koa-generic-session')
const koaRedis = require('koa-redis');
const cors = require('koa2-cors'); // 跨域配置

const { sessionInfo, cookieInfo, redisInfo, corsOrigin } = require('./config/config')

const crawlerRouter = require('./routes/crawler');
const indexRouter = require('./routes/index');
const adminRouter = require('./routes/admin');
 
// error handler
onerror(app);

app.use(cors({
  origin: function(ctx){
    return corsOrigin // 配置端口为3001的都可以跨域访问
  },
  credentials: true, // 服务端运行 跨域设置session
}));

// middlewares
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'ejs'
}))

app.keys = sessionInfo.keys; // 加密cookie

app.use(session({
  key: sessionInfo.name, // cookie的name
  prefix: sessionInfo.prefix, // redis的前缀 key
  cookie: cookieInfo,
  store: koaRedis(redisInfo)
}));

// routes definition
app.use(crawlerRouter.routes(), crawlerRouter.allowedMethods());
app.use(indexRouter.routes(), indexRouter.allowedMethods());
app.use(adminRouter.routes(), adminRouter.allowedMethods());
 
// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app;
